package com.zenagro.actions;

import java.io.*;
import java.util.*;

import javax.inject.*;

import org.apache.commons.fileupload.*;
import org.openxava.actions.*;
import org.openxava.jpa.*;
import org.openxava.model.*;
import org.openxava.util.*;
import org.openxava.view.*;

import com.zenagro.domain.zenagro.*;
import com.zenagro.domain.zenagro.base.*;
import com.zenagro.utils.*;

public class ProcessFileAction  extends UpdateAction
    implements INavigationAction, IProcessLoadedFileAction  {          // 1
 
	
	@Inject HashMap mapaComun;
	
	 private List fileItems;
 
    public void execute() throws Exception {
    	//super.execute();
        Iterator i = getFileItems().iterator();   
 
        while (i.hasNext()) {
            FileItem fi = (FileItem)i.next();                         // 3
            String filename = fi.getName();
            if (!Is.emptyString(filename)) {
            	String nombreModelo=this.getModelName();
              
                File folderModel=new File(FileEntityUtils.pathRepo+File.separator+nombreModelo);
                if (!folderModel.exists()) {
    				folderModel.mkdir();
    			}
                Map keyValues=(Map)mapaComun.get(this.getView().getModelName());
                String path=folderModel.getAbsolutePath()+File.separator+keyValues.get("id");
                File fileTemp=new File(path);
                if (fileTemp.exists()) {
    				Files.deleteDir(fileTemp);
    			}
                fileTemp.mkdir();
                File fileUpload=new File(fileTemp.getAbsolutePath()+File.separator+filename);
                
                fi.write(fileUpload);
                System.out.println(fileUpload.getAbsolutePath());
                
                FileIdentificable entity=(FileIdentificable)MapFacade.findEntity(nombreModelo, ((HashMap)mapaComun.get(nombreModelo)));
                entity.setFile(nombreModelo+File.separator+keyValues.get("id")+File.separator+fileUpload.getName());
                XPersistence.commit();
            	XPersistence.getManager().merge(entity);
                
            }
         
            
            
        }
    }

    public String[] getNextControllers() {
   	 return new String [] { "UploadFile" };
   }
    public String getCustomView() {
        return DEFAULT_VIEW;
    }
 
    public List getFileItems() {
        return fileItems;
    }
 
    public void setFileItems(List fileItems) {                        // 5
        this.fileItems = fileItems;
    }
    
}
